package com.itc.bpm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.itc.bpm.bean.BpmTaskFormValue;
import com.itc.bpm.mapper.BpmTaskFormValueMapper;
import com.itc.bpm.service.BpmTaskFormValueService;
import com.itc.bpm.util.JsonUtils;
import com.itc.common.core.utils.DateUtils;
import com.itc.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BpmTaskFormValueServiceImpl extends ServiceImpl<BpmTaskFormValueMapper,BpmTaskFormValue> implements BpmTaskFormValueService {
    @Override
    public BpmTaskFormValue findLastRecord(String taskId) {
        return this.getOne(new LambdaQueryWrapper<BpmTaskFormValue>().eq(BpmTaskFormValue::getTaskId,taskId).orderByDesc(BpmTaskFormValue::getCreateTime).last("limit 1"));
    }

    @Override
    public List<ObjectNode> selectTaskHistoryData(String taskId) {
        List<BpmTaskFormValue> values = this.list(new LambdaQueryWrapper<BpmTaskFormValue>().eq(BpmTaskFormValue::getTaskId,taskId).orderByDesc(BpmTaskFormValue::getCreateTime));
        List<ObjectNode> result = new ArrayList<>();
        if(values!=null && values.size()>0){
            for(BpmTaskFormValue bpmTaskFormValue:values){
                if(StringUtils.isNotEmpty(bpmTaskFormValue.getFromValue())){
                    ObjectNode node = JsonUtils.jsonToObject(bpmTaskFormValue.getFromValue(),ObjectNode.class);
                    // 创建时间封装进入
                    String data = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", bpmTaskFormValue.getCreateTime());
                    node.put("createTime", data);
                    node.put("createBy", bpmTaskFormValue.getCreateBy());
                    node.put("status",bpmTaskFormValue.getStatus());
                    node.put("serviceId",bpmTaskFormValue.getId());
                    node.put("taskId",taskId);
                    node.put("rebackReason",bpmTaskFormValue.getRebackReason());
                    node.put("rebackDate",bpmTaskFormValue.getRebackDate()+"");
                    node.put("rebackUser",bpmTaskFormValue.getRebackUser());
                    node.put("isReback",bpmTaskFormValue.getIsReback());
                    result.add(node);
                }
            }
        }
        return result;
    }

    @Override
    public BpmTaskFormValue findRebackLastRecord(String taskId) {
        return this.getOne(new LambdaQueryWrapper<BpmTaskFormValue>().eq(BpmTaskFormValue::getTaskId,taskId).eq(BpmTaskFormValue::getIsReback,1).orderByAsc(BpmTaskFormValue::getRebackDate).last("limit 1"));
    }
}
